import os
import json
import csv
from engine.baidu.translate import t_baidu
from engine.youdao.translate import t_yuodao
from utils import get_length
import time
from rich.console import Console
from utils import *
console = Console()

class D:
    def __init__(self):
        self.configs=None
        self.engines=None
        self.jobs=None
        self.res=[]
        self.header=["name"]


    def start(self):
        try:
            if os.path.exists("settings.json") and os.path.exists("jobs.json"):
                with open("./settings.json","r",encoding="utf-8")as f:
                    content=f.read()
                self.configs=dict(json.loads(str(content)))
                self.engines=self.configs.keys()
                self.show_msg("info","使用引擎"+str(self.engines))
                with open("./jobs.json","r",encoding="utf-8")as f:
                    content=f.read()
                self.jobs=dict(json.loads(str(content)))
                self.show_msg("info","待翻译文字"+str(self.jobs))
                for i in (self.configs[list(self.engines)[0]]["language"]).keys():
                    self.header.append(i)
                # self.doit()
            else:
                self.show_msg("warn","缺少配置文件settings.json、jobs.josn")
        except:
            self.show_msg("error", "未知错误")
    def doit(self):
        if len(self.engines)==0:
            self.show_msg("info","请先配置好引擎")
        elif len(self.engines)==1:
            if list(self.engines)[0] not in ["baidu","youdao"]:
                self.show_msg("info","当前仅限于有道、百度翻译API")
            else:
                self.one_engine()
        elif len(self.engines)==2:
            if list(self.engines)[0] not in ["baidu","youdao"] or list(self.engines)[1] not in ["baidu","youdao"]:
                self.show_msg("info","当前仅限于有道、百度翻译API")
            else:
                self.two_engine()
        else:
            self.show_msg("info","当前仅限于有道、百度翻译API")
    def one_engine(self):
        engine=list(self.engines)[0]
        language=self.configs[engine]["language"]
        id=self.configs[engine]["appid"]
        key=self.configs[engine]["appkey"]
        for name,word in zip(self.jobs.keys(),self.jobs.values()):
            self.show_msg("info","----------------------------开始翻译'"+word+"'------------------------------")
            temp_result=[name]
            for l in language.keys():
                if(l=="简体中文"):
                    self.show_msg("info",l+":"+word)
                    temp_result.append(word)
                else:
                    if engine=="baidu":
                        res=t_baidu(word,id,key,kind=language[l])
                    elif engine=="youdao":
                        res=t_yuodao(word,id,key,kind=language[l])
                    if res=="1error":
                        temp_result.append("！翻译失败！")
                    else:
                        temp_result.append(res)
                    self.show_msg("info",l+":"+res)
                time.sleep(1)
            self.res.append(temp_result)
            self.save_res()
    def two_engine(self):
        baidu_language=self.configs["baidu"]["language"]
        youdao_language=self.configs["youdao"]["language"]
        
        id_baidu=self.configs["baidu"]["appid"]
        id_youdao=self.configs["youdao"]["appid"]
        key_baidu=self.configs["baidu"]["appkey"]
        key_youdao=self.configs["youdao"]["appkey"]

        # id=config[engine]["appid"]
        # key=config[engine]["appkey"]
        for name,word in zip(self.jobs.keys(),self.jobs.values()):
            self.show_msg("info","----------------------------开始翻译'"+word+"'------------------------------")
            temp_result=[name]
            for baidu_l,youdao_l in zip(baidu_language.keys(),youdao_language.keys()):
                if(baidu_l=="简体中文"):
                    self.show_msg("info",baidu_l+":"+word+"("+str(get_length(word))+")|"+word+"("+str(get_length(word))+")\t\t=>"+word)
                    temp_result.append(word)
                else:
                    res_baidu=t_baidu(word,id_baidu,key_baidu,kind=baidu_language[baidu_l])
                    res_yoduao=t_yuodao(word,id_youdao,key_youdao,kind=youdao_language[youdao_l])
                    if res_baidu=="1error" and res_yoduao=="1error":
                        res="dd翻译失败"
                    elif res_baidu!="1error" and res_yoduao=="1error":
                        res=res_baidu
                    elif res_baidu=="1error" and res_yoduao!="1error":
                        res=res_yoduao
                    elif res_baidu!="1error" and res_yoduao!="1error":
                        if get_length(res_baidu)<=get_length(res_yoduao):res=res_baidu
                        else:res=res_yoduao
                    temp_result.append(res)
                    self.show_msg("info",baidu_l+":"+res_baidu+"("+str(get_length(res_baidu))+")|"+res_yoduao+"("+str(get_length(res_yoduao))+")\t\t=>"+res)
                time.sleep(1)
            self.res.append(temp_result)
            self.save_res()
        # self.save_res()
    def save_res(self):
        self.show_msg("info","----------------------------开始保存结果------------------------------")
        with open('score.csv','w',encoding='utf8',newline='') as f :
            writer = csv.writer(f)
            writer.writerow(self.header)
            writer.writerows(self.res)
        self.show_msg("info","----------------------------结果保存完成------------------------------")
        
    def show_msg(self, cate, txt):
        try:
            if cate == "info": start = "[bold green](info):[not bold][green]"
            if cate == "warn": start = "[bold yellow](warn):[not bold][green]"
            if cate == "error": start = "[bold red](error):[not bold][green]"
            console.print(start + txt)
        except:self.show_msg("error", "show_msg模块出错")
if __name__=='__main__':
    d = D()
    d.start()
    d.doit()
